import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:self32/widget/model/auth_model.dart';
import '../entity/reader_entity.dart';
import '../event/user_id_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../socket/socket_manager.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import '../widget/app_bar.dart';
import '../widget/custom_floating_action_button_location.dart';
import '../widget/float_button.dart';
import '../widget/model/list_model.dart';

class Query extends StatefulWidget {
  const Query({Key? key}) : super(key: key);

  @override
  State<Query> createState() => _QueryState();
}

class _QueryState extends State<Query> {

  SocketManager manager = SocketManager();

  var step = 1;

  String keyword = '';
  ListModel model = ListModel();

  StreamSubscription? userSubscription;

  @override
  initState() {
    super.initState();

    userSubscription = eventFactory.on<UserIdEvent>().listen((event) {
      // currentTask.uid = event.uid;
      _getUser(event.uid);
    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        currentTask.clear();
        timer.cancel();
        manager.setMode(Mode.none);
        Get.back();
      });
    });
  }

  _searchBarWidget(){
    return Container(
        decoration:BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(16.r)),
        ),
        padding: EdgeInsets.only(left: 4.w,right: 1.5.w,top: 1.5.h,bottom: 1.5.h),
        margin:  EdgeInsets.only(left: 12.w, right: 12.w,top: 10.h,bottom: 10.h),
        child: Row(
          children: [
            const Icon(Icons.search),
            SizedBox(width: 4.w,),
            SizedBox(
              width: 184.w,
              child: TextField(
                minLines: 1,
                textInputAction: TextInputAction.search,
                onChanged: (input){
                  keyword = input;
                  model.filterList(keyword);
                },
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.only(top: 6.h,bottom: 6.h),
                  isCollapsed: true,
                  border: InputBorder.none,
                  hintText: "搜索书籍名称 书籍编号等",
                ),
                style: TextStyle(color: Colors.black,fontSize: 8.sp)
              ),
            ),
          ],
        )
    );
  }

  _getUser(uid) async {
    manager.setMode(Mode.none);
    ReaderEntity? reader = await findReader(uid);
    if(reader != null && reader.no != null && reader.no!.isNotEmpty){
      currentTask.uid = reader.no;
      currentTask.uName = reader.name;
      currentTask.readerEntity = reader;
      setState(() {
        step = 2;
      });
    }else{
      toastWarn('身份未认证');
      currentTask.clear();
    }
  }


  _title(){
    return Container(
        margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w,bottom: 10.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                currentTask.clear();
                timer.cancel();
                manager.setMode(Mode.none);
                Get.back();
              },
              child: Image.asset("assets/images/back.png", width: 40.w, fit: BoxFit.fitWidth,),
            ),
            Text("借阅查询",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
            Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),))
          ],
        )
    );
  }


  @override
  void dispose() {
    userSubscription?.cancel();
    userSubscription = null;
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton:floatButton(),
      floatingActionButtonLocation:CustomFloatingActionButtonLocation(
          FloatingActionButtonLocation.endFloat, 0,-60.h),
      body: Stack(
        children: [
          Container(
              width: double.infinity,
              height: double.infinity,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage(
                    "assets/images/bg.png",
                  ),
                ),
              ),
              child: Column(
                children: [
                  appBar(),
                  _title(),
                  if(step == 1)...[
                    AuthModel().show()
                  ],
                  if(step == 2)...[
                    _searchBarWidget(),
                    model.show(currentTask.readerEntity!.currentBorrowList,filter: keyword),
                  ],
                ],
              )
          ),

        ]
      )
    );
  }
}